


let routes = new Map()

export function RegisterApi(route, methods, handler) {
    routes.set(route, { methods: methods, handler: handler })
}

export async function CallApi(route, request) {
    if (routes.has(route)) {
        let api = routes.get(route)
        if (api.methods.includes(request.method)) {
            if (request.body) {
                let reader = request.body.getReader()
                let data = ''
                while (true) {
                    let rd = await reader.read()
                    if (rd.done) {
                        break;
                    }
                    data += new TextDecoder('utf-8').decode(rd.value);

                }
                try {
                    request.data = JSON.parse(data)
                } catch (error) {
                    // failed to parse body to object, return string as data
                    request.data = data;
                }
            }
            return api.handler(request)
        } else {
            return new Response('Not allow', { status: 405 })
        }
    } else {
        return new Response('Not found', { status: 404 })
    }
}
